import type {FC} from 'react';
import {useState, useEffect} from 'react';
import {Form, Button, Col, Input, Popover, Progress, Row, Select, message} from 'antd';
import type {Store} from 'antd/es/form/interface';
import {Link, useRequest, history} from 'umi';
// import type {StateType} from './service';
import {doRegister, doCaptcha} from '@/services/ant-design-pro/api';

import styles from './style.less';

const FormItem = Form.Item;
const {Option} = Select;
const InputGroup = Input.Group;

const passwordStatusMap = {
  ok: (
    <div className={styles.success}>
      <span>强度：强</span>
    </div>
  ),
  pass: (
    <div className={styles.warning}>
      <span>强度：中</span>
    </div>
  ),
  poor: (
    <div className={styles.error}>
      <span>强度：弱</span>
    </div>
  ),
};

const passwordProgressMap: {
  ok: 'success';
  pass: 'normal';
  poor: 'exception';
} = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

const Register: FC = () => {
  const [count, setCount]: [number, any] = useState(0);
  const [visible, setVisible]: [boolean, any] = useState(false);
  const [prefix, setPrefix]: [string, any] = useState('86');
  const [popover, setPopover]: [boolean, any] = useState(false);
  const confirmDirty = false;
  let interval: number | undefined;
  const [form] = Form.useForm();

  useEffect(
    () => () => {
      clearInterval(interval);
    },
    [interval],
  );

  const onGetCaptcha = async () => {

    const username = form.getFieldValue('username');
    if (!username) {
      message.error('请输入注册手机号');
    } else {
      try {
        const msg = await doCaptcha(username);
        console.log(msg);
        if (msg.status === 'ok') {
          let counts = 59;
          if (msg.data) {
            form.setFieldsValue({code: msg.data});
          }
          setCount(counts);
          interval = window.setInterval(() => {
            counts -= 1;
            setCount(counts);
            if (counts === 0) {
              clearInterval(interval);
            }
          }, 1000);
        } else {
          message.error("发送失败");
        }
      } catch (error) {
      }
    }
  };

  const pattern_1 = /^.*([0-9])+.*$/i; //数字
  const pattern_2 = /[a-z]/; //小写字母
  const pattern_3 = /[A-Z]/; //大写字母
  const pattern_4 = /[`~!@#$%^&*()\-_+=\\|{}':;\",\[\].<>\/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]/; //特殊字符
  const getPwdStrength = (pwd: string): 0 | 1 | 2 | 3 => {
    let level = 0;
    if (pwd) {
      pwd = pwd.trim();
      if (pwd.length >= 8) {
        if (pattern_1.test(pwd)) {
          level++;
        }
        if (pwd.length > 10) {
          level++;
        }
        if (pattern_2.test(pwd) || pattern_3.test(pwd)) {
          level++;
        }
        if (pattern_4.test(pwd)) {
          level++;
        }
        if (level > 3) {
          level = 3;
        }
      }
    }
    return level as 0 | 1 | 2 | 3;
  };
  const getPasswordStatus = () => {
    const value = form.getFieldValue('password');
    const level = getPwdStrength(value);
    if (level >= 3) {
      return 'ok';
    }
    if (level >= 2) {
      return 'pass';
    }
    return 'poor';
  };

  const {loading: submitting, run: register} = useRequest<{ data: API.Result<API.RegisterResult> }>(doRegister, {
    manual: true,
    onSuccess: (data, params) => {
      if (data.status === 'ok') {
        debugger;
        message.success('注册成功！');
        console.log("---1",params)
        history.push({
          pathname: '/user/register-result',
          state: {
            account: params[0].username,
          },
        });
      }
    },
  });
  const onFinish = (values: Store) => {
    register(values);
  };

  const checkConfirm = (_: any, value: string) => {
    const promise = Promise;
    if (value && value !== form.getFieldValue('password')) {
      return promise.reject('两次输入的密码不匹配!');
    }
    return promise.resolve();
  };

  const checkPassword = (_: any, value: string) => {
    const promise = Promise;
    // 没有值的情况
    if (!value) {
      setVisible(!!value);
      return promise.reject('请输入密码!');
    }

    // console.log(value, value.length < 8, /^\d+$/.test(value))
    if (value.length < 8 || /^\d+$/.test(value)) {
      return promise.reject('密码不能为纯数字且长度不少于8位');
    }
    // 有值的情况
    if (!visible) {
      setVisible(!!value);
    }
    setPopover(!popover);
    if (value && confirmDirty) {
      form.validateFields(['confirm']);
    }
    return promise.resolve();
  };

  const changePrefix = (value: string) => {
    setPrefix(value);
  };

  const renderPasswordProgress = () => {
    const value = form.getFieldValue('password');
    const passwordStatus = getPasswordStatus();
    let pwdStrength = getPwdStrength(value);
    let percent = 0;
    if (pwdStrength > 0) {
      percent = getPwdStrength(value) * 3 / 9 * 100
    }
    // console.log(percent)
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={8}
          steps={9}
          percent={percent}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  return (
    <div className={styles.register}>
      <div className={styles.header}>
        用户注册
      </div>
      <div className={styles.main}>
        <Form form={form} name="UserRegister" onFinish={onFinish} initialValues={{
          username: '',
          company: '',
          password: '',
          confirm: '',
        }}>
          <InputGroup compact>
            <Select size="large" value={prefix} onChange={changePrefix} style={{width: '20%'}}>
              <Option value="86">+86</Option>
            </Select>
            <FormItem
              style={{width: '80%'}}
              name="username"
              rules={[
                {
                  required: true,
                  message: '请输入手机号!',
                },
                {
                  pattern: /^\d{11}$/,
                  message: '手机号格式错误!',
                },
              ]}
            >
              <Input size="large" placeholder="请输入注册手机号"/>
            </FormItem>
          </InputGroup>

          <FormItem
            name="company"
            rules={[
              {
                required: true,
                message: '请输入公司名称!',
              },
            ]}
          >
            <Input size="large" placeholder="公司名称"/>
          </FormItem>
          <Popover
            getPopupContainer={(node) => {
              if (node && node.parentNode) {
                return node.parentNode as HTMLElement;
              }
              return node;
            }}
            content={
              visible && (
                <div style={{padding: '4px 0'}}>
                  {passwordStatusMap[getPasswordStatus()]}
                  {renderPasswordProgress()}
                  <div style={{marginTop: 10}}>
                    <span>请至少输入 8 个字符。不能用纯数字作为密码。请不要使用容易被猜到的密码。</span>
                  </div>
                </div>
              )
            }
            overlayStyle={{width: 240}}
            placement="right"
            visible={visible}
          >
            <FormItem
              name="password"
              className={
                form.getFieldValue('password') &&
                form.getFieldValue('password').length > 0 &&
                styles.password
              }
              rules={[
                {
                  validator: checkPassword,
                },
              ]}
            >
              <Input size="large" type="password" placeholder="至少8位密码，区分大小写"/>
            </FormItem>
          </Popover>
          <FormItem
            name="confirm"
            rules={[
              {
                required: true,
                message: '确认密码',
              },
              {
                validator: checkConfirm,
              },
            ]}
          >
            <Input size="large" type="password" placeholder="确认密码"/>
          </FormItem>

          <Row gutter={8}>
            <Col span={16}>
              <FormItem
                name="code"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码!',
                  },
                ]}
              >
                <Input size="large" placeholder="验证码"/>
              </FormItem>
            </Col>
            <Col span={8}>
              <Button
                size="large"
                disabled={!!count}
                className={styles.getCaptcha}
                onClick={onGetCaptcha}
              >
                {count ? `${count} s` : '获取验证码'}
              </Button>
            </Col>
          </Row>
          <FormItem>
            <Button
              size="large"
              loading={submitting}
              className={styles.submit}
              type="primary"
              htmlType="submit"
            >
              <span>注册</span>
            </Button>
            <Link className={styles.login} to="/user/login">
              <span>使用已有账户登录</span>
            </Link>
          </FormItem>
        </Form>
      </div>
    </div>
  );
};
export default Register;
